package jmotioncapture.calculation;

import java.util.Iterator;

import jmotioncapture.camera.FrameSet;
import jmotioncapture.camera.Frame;
import jmotioncapture.geometry2D.Point;

/**
 * 
 * @author Kenneth
 * @since 1.0.0
 */
public class FrameCalculation {

	/**
	 * Tolerance of static point. If set to 10, that mean each the distance
	 * current point and the reference point cannot lager then 10pixel.<br>
	 */
	public static double STATIC_POINT_TOLERANCE = 5;

	public static int NUMBER_OF_FRAMES_DECIDE_STATIC_POINT = 50;

	/**
	 * 
	 * @param point
	 * @param frameSet
	 * @return
	 * @since 1.0.0
	 */
	public static boolean isStaticPoint(Point point, FrameSet frameSet) {

		short turn = 5;

		for (int i = 0; i < turn; i++) {
			for (int j = i; j < frameSet.size(); j = j + turn) {
				if (GeomCalculation.distance(nearestPoint(point, frameSet
						.frameAt(j)), point) > FrameCalculation.STATIC_POINT_TOLERANCE)
					return false;
			}
		}
		return true;
	}

	/**
	 * 
	 * @param refPoint
	 * @param frame
	 * @return
	 * @since 1.0.0
	 */
	public static Point nearestPoint(Point refPoint, Frame frame) {
		Iterator<Point> itPt = frame.getPoints().iterator();

		Point nearestPt = null, pt = null;

		double minDistance = Double.MAX_VALUE;

		while (itPt.hasNext()) {
			pt = itPt.next();
			double distance = GeomCalculation.distance(refPoint, pt);
			if (distance < minDistance) {
				minDistance = distance;
				nearestPt = pt;
			}
		}

		return nearestPt;
	}

	public static FrameSet filterStaticDynamicPoints(FrameSet farmeSet, Frame frame) {
		FrameSet result = new FrameSet();
		Frame dynamicFrame = new Frame();
		Frame staticFrame = new Frame();

		Iterator<Point> itPt = frame.getPoints().iterator();
		while (itPt.hasNext()) {
			Point refPoint = itPt.next();
			if (isStaticPoint(refPoint, farmeSet))
				staticFrame.addPoint(refPoint);
			else
				dynamicFrame.addPoint(refPoint);
		}

		result.addFrame(dynamicFrame);
		result.addFrame(staticFrame);
		return result;
	}
}
